/**
 *
 */
package com.ybkj.daijia.api.driver.v3;

import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.driver.Error;
import com.ybkj.daijia.api.driver.ErrorConstant;
import com.ybkj.daijia.api.driver.SecurityUtils;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Area;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.ZhuancheService;
import com.ybkj.daijia.server.zhuan.Car;
import com.ybkj.daijia.server.zhuan.CarType;
import com.ybkj.daijia.server.zhuan.Order;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author bo
 *
 */
@Controller("driverZhuanProcessController")
@RequestMapping(value = "driver/api/rest/v3")
public class ZhuanProcessController {

    private static final Logger logger = LoggerFactory.getLogger(ZhuanProcessController.class);

    @Autowired
    private DriverService driverService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ZhuancheService zhuancheService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    /**
     * 补单
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "fillOrderZhuan", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport fillOrderZhuan(
        Long driverID,
        String fromPlace, Double clientLongitude, Double clientLatitude,
        String clientName, String clientPhone, Long serverTimeStamp,
        String appKey, String token, String timestamp) {

        logger.debug(
            "recv driverID:{},fromPlace:{},clientLongitude:{},clientLatitude:{},clientName:{},clientPhone:{},serverTimeStamp:{},appKey:{},token:{},timestamp:{}",
            driverID, fromPlace, clientLongitude, clientLatitude, clientName, clientPhone,
            serverTimeStamp, appKey, token, timestamp);

        if (null == driverID || null == fromPlace || null == clientLongitude
            || null == clientLatitude ||
            StringUtils.isBlank(clientPhone) || null == serverTimeStamp ||
            SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverID));
        params.add(String.valueOf(fromPlace));
        params.add(String.valueOf(clientLongitude));
        params.add(String.valueOf(clientLatitude));
        params.add(String.valueOf(clientName));
        params.add(String.valueOf(clientPhone));
        params.add(String.valueOf(serverTimeStamp));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Driver driver = driverService.findOne(driverID);

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
            }
            if (driver.getIsFreeze()) {
                return ResultTransport.getErrorBy(ErrorConstant.USER_IS_FREEZE_ERROR);
            }
            if (driver.getStatus().equals(Driver.DRIVER_OFFLINE)) {
                return ResultTransport.getErrorBy(new Error(-27, "未上班，不能补单"));
            } else if (!driver.getStatus().equals(Driver.DRIVER_ONLINE)) {
                return ResultTransport.getErrorBy(new Error(-27, "忙碌中，不能补单"));
            }

            if (!driver.getDriverJobType().equals(Driver.DriverJobType.all)) {
                if (!driver.getDriverJobType().contains(Driver.DriverJobType.zhuanche.toString())) {
                    return ResultTransport.getErrorBy(ErrorConstant.ORDER_IS_ZHUANCHE_ERROR);
                }
            }

            if (null == driver.getCarId()) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_HAS_NO_CAR);
            }

            Car car = zhuancheService.findCar(driver.getCarId());
            if (null == car) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_HAS_NO_CAR);
            }

            if (null == car.getCarTypeId()) {
                return ResultTransport.getErrorBy(ErrorConstant.CAR_HAS_NO_CARTYPE);
            }

            CarType carType = zhuancheService.findCarType(car.getCarTypeId());
            if (null == carType) {
                return ResultTransport.getErrorBy(ErrorConstant.CAR_HAS_NO_CARTYPE);
            }

            Order order = new Order();

            order.setStartAddress(fromPlace);
            order.setStartLng(clientLongitude);
            order.setStartLat(clientLatitude);
            order.setPassengerName(clientName);
            order.setPassengerPhone(clientPhone.replaceAll(" ", ""));
            order.setChannelName(Order.ORDER_TYPE_BUDAN);
            order.setServerTime(new Date(serverTimeStamp));
            order.setStatus(Order.ORDER_STATUS_NEW);

            Passenger passenger = memberService.findOnePassengerByPhone(order.getPassengerPhone());

            Result<Order> result = zhuancheService.fillOrder(order, driver, carType);

            if (!result.isSuccess()) {
                return ResultTransport.getErrorBy(new Error(-4, result.getMessage()));
            }

            if (null == passenger) {
                passenger = memberService.findOnePassengerByPhone(order.getPassengerPhone());
                ReactorVo rVo = new ReactorVo();
                rVo.setPassenger(passenger);
                rVo.setActivityEvent(ActivityEvent.newRegister);
                ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                applicationEventMulticaster.multicastEvent(activityCheckEvent);
            }

            Order o = zhuancheService.findOne(result.getResult().getId());
            Area area = areaService.findOneWithCharge(o.getAreaId());
            o.setArea(area);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS); //补单成功
            instance.setData(o);

            return instance;

        } catch (Exception e) {
            logger.error("api v3 driver fillOrderZhuan error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }


}